package com.example.zxw.ui.news

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.animation.core.tween
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
import androidx.compose.animation.with
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.ScrollableTabRow
import androidx.compose.material3.Tab
import androidx.compose.material3.TabRowDefaults.tabIndicatorOffset
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
import androidx.compose.ui.input.nestedscroll.NestedScrollSource
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.Velocity
import androidx.compose.ui.unit.dp
import androidx.compose.ui.zIndex
import androidx.fragment.app.viewModels
import androidx.lifecycle.LifecycleCoroutineScope
import androidx.lifecycle.ViewModel
import com.example.zxw.R
import com.example.zxw.TestAnimatedList
import com.example.zxw.entity.ChannelEntity
import com.example.zxw.entity.HotWordsEntity
import com.example.zxw.test.TestSmartRefresh
import com.example.zxw.ui.news.newstabpage.CommentNewsTabPage
import com.example.zxw.ui.views.smartrefresh.CnsSmartRefresh
import com.example.zxw.ui.views.smartrefresh.RefreshState
import com.fmt.mvi.learn.gobal.log
import com.google.accompanist.pager.ExperimentalPagerApi
import com.google.accompanist.pager.HorizontalPager
import com.google.accompanist.pager.PagerState
import com.google.accompanist.pager.rememberPagerState
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.concurrent.timer


class NewsFragment : Fragment() {

    private val newsViewModel: NewsViewModel by viewModels()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View {

        return ComposeView(inflater.context).apply {
            layoutParams = ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT
            )
            setContent {
                NewsPage()
            }
        }
    }

    private val searchShape = RoundedCornerShape(30.dp)

    @OptIn(ExperimentalPagerApi::class)
    @Composable
    fun NewsPage() {
        val state = newsViewModel.newPageUiState.collectAsState()
        val hotWords = state.value.hotWordsList


        val mockDatas = remember {
            mutableStateListOf<String>()
        }

        LaunchedEffect(key1 = Unit, block = {
            for(i in 0..20){
                mockDatas.add("$i")
            }
        })

        var pageIndex = remember {
            mutableStateOf(1)
        }

        Column {
            "新闻页".log()
            //顶部搜索区域
            TopArea(hotWords)
            //内容区域
            if (state.value.isLoading) {
                Box(Modifier.fillMaxSize()) {
                    Text(text = "加载中...", modifier = Modifier.align(Alignment.Center))
                }
            } else if (!state.value.isSuccess) {
                Box(Modifier.fillMaxSize()) {
                    Text(text = "加载失败", modifier = Modifier.align(Alignment.Center))
                }
            } else {
                val selectIndex = rememberPagerState(initialPage = 0)
                val channelEntityList = state.value.channelEntityList
                ChannelTabLayout(channelEntityList, selectIndex)
                var isShowing: Boolean = false
                HorizontalPager(count = channelEntityList.size, state = selectIndex) { page ->
                    //只在状态发生变化时进行重组
                    if (isShowing) {
                        if (page != selectIndex.currentPage) {
                            isShowing = false
                        }
                    } else {
                        if (page == selectIndex.currentPage) {
                            isShowing = true
                        }
                    }
                    isShowing = page == selectIndex.currentPage


                    var isFreshing by remember {
                        mutableStateOf(false)
                    }
                    Box(modifier = Modifier.fillMaxSize()) {
                        //tab对应内容区域
                        if(channelEntityList[page].cname=="home"){
                            CommentNewsTabPage(channelEntityList[page], isShowing)
                        }else{
                            Text(text = "待开发")
                        }

                    }
                }
            }
        }
    }

    @OptIn(ExperimentalPagerApi::class)
    @Composable
    fun ChannelTabLayout(channelEntityList: List<ChannelEntity>, pagerState: PagerState) {
        val scope = rememberCoroutineScope()
        val currentSelect = pagerState.currentPage
        ScrollableTabRow(
            selectedTabIndex = currentSelect,
            containerColor = Color.White,
            modifier = Modifier
                .fillMaxWidth()
                .wrapContentSize(),
            indicator = { positions ->//设置滑动条的属性，默认是白色的
                Box(modifier = Modifier.tabIndicatorOffset(positions[currentSelect])) {
                    Box(
                        modifier = Modifier
                            .width(12.dp)
                            .height(2.dp)
                            .background(Color.Red)
                            .align(Alignment.BottomCenter)
                    )
                }
            },
            divider = {// 底部的分割线
            },
            edgePadding = 0.dp
        ) {
            channelEntityList.forEachIndexed { index, entity ->
                Tab(selected = index == currentSelect,
                    onClick = {
                        scope.launch {
                            pagerState.animateScrollToPage(index)
                        }
                    }) {
                    Box(modifier = Modifier.height(38.dp)) {
                        Text(
                            text = entity.name,
                            modifier = Modifier
                                .align(Alignment.Center)
                                .padding(horizontal = 10.dp),
                            textAlign = TextAlign.Center,
                            style = TextStyle(color = if (index == currentSelect) Color.Black else Color.Gray)
                        )
                    }
                }
            }
        }
    }

    @Composable
    fun TopArea(hotWords: List<HotWordsEntity>) {
        "TopArea".log()
        Row(
            modifier = Modifier
                .background(Color.White)
                .statusBarsPadding()
                .padding(horizontal = 10.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Image(
                painter = painterResource(id = R.drawable.pic_cns),
                contentDescription = "",
                Modifier
                    .width(64.dp)
                    .height(24.dp)
            )
            Box(
                modifier = Modifier
                    .weight(1f)
                    .height(30.dp)
                    .padding(horizontal = 10.dp)
                    .clip(searchShape)
                    .background(colorResource(id = R.color.color_f2f2f2))
            ) {
                ViewFlipper(hotWords)
            }
            Image(
                painter = painterResource(id = R.drawable.icon_more_action),
                contentDescription = "",
                Modifier
                    .width(30.dp)
                    .height(30.dp)
            )
        }
    }


    @OptIn(ExperimentalAnimationApi::class)
    @Composable
    fun ViewFlipper(hotWords: List<HotWordsEntity>) {

        if (hotWords.isEmpty()) {
            Box(modifier = Modifier.fillMaxSize()) {
                Text(
                    text = "搜索",
                    textAlign = TextAlign.Center,
                    modifier = Modifier
                        .wrapContentSize()
                        .align(Alignment.Center)
                )
            }

        } else {
            var currentIndex by remember {
                mutableStateOf(0)
            }

            DisposableEffect("") {
                val timer = timer(initialDelay = 3000L, period = 3000L) {
                    if (isVisible) {
                        if (currentIndex + 1 >= hotWords.size) {
                            currentIndex = 0
                        } else {
                            currentIndex += 1
                        }
                    }
                }

                onDispose {
                    timer.cancel()
                }

            }

            AnimatedContent(
                targetState = currentIndex,
                modifier = Modifier.fillMaxSize(),
                transitionSpec = {
                    slideInVertically(tween(1000)) {
                        it
                    } with slideOutVertically(tween(1000)) {
                        -it
                    }
                }) { index ->
                val content = hotWords[index].name
                Box(modifier = Modifier.fillMaxSize()) {
                    Text(
                        text = content,
                        textAlign = TextAlign.Center,
                        modifier = Modifier
                            .wrapContentSize()
                            .align(Alignment.Center)
                    )
                }

            }
        }


    }


}